package com.haixiaoke.saas.department.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.config.OssConfig;
import com.haixiaoke.saas.common.constant.TenantConstants;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.oss.AliOssServiceImpl;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.contract.fadada.service.FaDaDaService;
import com.haixiaoke.saas.department.domain.BizTenantMenu;
import com.haixiaoke.saas.department.domain.ElectronicVisa;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.mapper.TenantMapper;
import com.haixiaoke.saas.department.service.IBizTenantMenuService;
import com.haixiaoke.saas.department.service.IElectronicVisaService;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.lock.domain.HouseLockSetting;
import com.haixiaoke.saas.lock.service.IHouseLockSettingService;
import com.haixiaoke.saas.setSwitch.service.ISetSwitchService;
import com.haixiaoke.saas.user.service.IBizTenantUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 机构信息Service业务层处理
 *
 * @author xiaolong
 * @date 2023-12-26
 */
@Service
public class TenantServiceImpl implements ITenantService {
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private AliOssServiceImpl aliOssService;
    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private IBizTenantMenuService iBizTenantMenuService;
    @Autowired
    private IBizTenantUserService iBizTenantUserService;
    @Autowired
    private ISetSwitchService setSwitchService;
    @Autowired
    private FaDaDaService faDaDaService;
    @Autowired
    private IElectronicVisaService electronicVisaService;

    @Autowired
    private IHouseLockSettingService houseLockSettingService;
    @Autowired
    private IHouseService houseService;

    /**
     * 查询机构信息
     *
     * @return 机构信息
     */
    @Override
    public Tenant selectDepartmentByDepId(String tenantId) {
        return tenantMapper.selectDepartmentByTenantId(tenantId);
    }

    /**
     * 查询机构信息列表
     *
     * @param department 机构信息
     * @return 机构信息
     */
    @Override
    public List<Tenant> selectDepartmentList(Tenant department) {
        List<Tenant> departments = tenantMapper.selectDepartmentList(department);
        // departments.forEach( x-> x.setTypeList( x.getType().split(",") ));
        return departments;
    }

    /**
     * 新增机构信息
     *
     * @param department 机构信息
     * @return 结果
     */
    @Override
    public int insertDepartment(Tenant department) {
        this.checkDepartment(department);
        Date nowDate = DateUtils.getNowDate();
        department.setCreateTime(nowDate);
        // department.setType(StringUtils.join(department.getTypeList(), ","));
        if (TenantConstants.DEP_PARENT_STATE_YES.equals(department.getDepParentState())) {
            department.setParentIds(StringUtils.join(department.getParentIdList(), ","));
        }
        int i = tenantMapper.insertDepartment(department);

        // 初始化订单审核开关
        setSwitchService.initializeSetSwitch(department.getTenantId());

        // 初始化锁设置
        HouseLockSetting houseLockSetting = new HouseLockSetting();
        houseLockSetting.setTenantId(department.getTenantId());
        houseLockSettingService.insertHouseLockSetting(houseLockSetting);

        return i;
    }

    /**
     * 修改机构信息
     *
     * @param department 机构信息
     * @param file
     * @return 结果
     */
    @Override
    public int updateDepartment(Tenant department, MultipartFile file) {
        Tenant byDepId = tenantMapper.selectDepartmentByDepId(department.getTenantId());
        if (!TenantContext.getTenantId().equals(byDepId.getTenantId())) {
            return 0;
        }

        if (department.getIntro().length() > 249) {
            throw new ServiceException("简介不能超过250个字");
        }

        Tenant department1 = new Tenant();
        department1.setTenantName(department.getTenantName());
        List<Tenant> departments = tenantMapper.selectDepartmentList(department1);
        if (CollectionUtil.isNotEmpty(departments)) {
            if (!byDepId.getTenantId().equals(department.getTenantId())) {
                throw new ServiceException("该机构名称已经存在");
            }
        }


        if (file != null) {
            String photoUrl = aliOssService.upload(ossConfig.getDepartmentIcon(), file.getOriginalFilename(), file);
            department.setIcon(photoUrl);
            //删除原始oss图片
            if (!StringUtils.isBlank(byDepId.getIcon())) {
                String path = department.getIcon();
                aliOssService.delete(path);
            }
        }
        department.setUpdateTime(DateUtils.getNowDate());
        return tenantMapper.updateDepartment(department);
    }

    /**
     * 批量删除机构信息
     *
     * @param depIds 需要删除的机构信息主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByDepIds(String[] depIds) {
        iBizTenantMenuService.deleteBizDepMenuByDepIds(depIds);
        iBizTenantUserService.deleteBizDepartmentUserByDepIds(depIds);
        return tenantMapper.deleteDepartmentByDepIds(depIds);
    }

    /**
     * 删除机构信息信息
     *
     * @param tenantId 机构信息主键
     * @return 结果
     */
    @Override
    public int deleteDepartmentByDepId(String tenantId) {
        return tenantMapper.deleteDepartmentByDepId(tenantId);
    }

    @Override
    public Tenant getElectronicVisaInfo() {
        Tenant department = tenantMapper.selectDepartmentByTenantId(TenantContext.getTenantId());
        // todo 还没有电子签表
        department.setContractTotalNumber(100);
        department.setContractUsedNumber(0);
        return department;
    }

    @Override
    public int manageUpdateDepartment(Tenant department) {
        this.checkDepartment(department);
        // department.setType(StringUtils.join(department.getTypeList(), ","));
        if (TenantConstants.DEP_PARENT_STATE_YES.equals(department.getDepParentState())) {
            department.setParentIds(StringUtils.join(department.getParentIdList(),","));
        }
        //校验用户数量
        int userNum = iBizTenantUserService.countUserNumByDepId(department.getTenantId());
        if (department.getMaxPopulation() < userNum && department.getMaxPopulation() != -1) {
            throw new ServiceException("用户最大数量小于当前机构用户数量");
        }

        //校验房屋数量
        int houseNum = houseService.countHouseNumByTenantId(department.getTenantId());
        if (department.getMaxHouse() < houseNum && department.getMaxHouse() != -1) {
            throw new ServiceException("房屋最大数量小于当前机构房屋数量");
        }

        Tenant tenant = tenantMapper.selectDepartmentByDepId(department.getTenantId());
        if (!StrUtil.equals(tenant.getContactsPhone(), department.getContactsPhone()) &&
                TenantConstants.ELECTRONIC_VISA_STATUS_OPEN.equals(tenant.getElectronicVisaStatus())) {
            department.setElectronicVisaStatus(TenantConstants.ELECTRONIC_VISA_STATUS_UN_OPEN);
            ElectronicVisa electronicVisa = electronicVisaService.selectElectronicVisaByTenantId(tenant.getTenantId());
            if (ObjectUtil.isNotEmpty(electronicVisa) && StrUtil.isNotBlank(electronicVisa.getOpenId())) {
                faDaDaService.corpUnbind(electronicVisa.getOpenId());
            }
        }
        department.setUpdateTime(DateUtils.getNowDate());
        return tenantMapper.updateDepartment(department);
    }

    @Override
    public Tenant selectDepByDepId(String tenantId) {
        Tenant tenant = tenantMapper.selectDepartmentByDepId(tenantId);
        tenant.setParentIdList(StrUtil.split(tenant.getParentIds(),","));
        return tenant;
    }

    /**
     * 设置机构权限菜单
     */
    @Override
    public int editMenuByDep(Tenant department) {
        //删除机构和菜单关联数据
        iBizTenantMenuService.deleteBizDepMenuByDepId(department.getTenantId());
        //批量插入机构和菜单的关联数据
        int rows = 1;
        List<BizTenantMenu> depMenuList = new ArrayList<>();
        for (Long menuId : department.getMenuIds()) {
            BizTenantMenu depMenu = new BizTenantMenu();
            depMenu.setTenantId(department.getTenantId());
            depMenu.setMenuId(menuId);
            depMenuList.add(depMenu);
        }
        if (!depMenuList.isEmpty()) {
            rows = iBizTenantMenuService.insertBatchDepMenu(depMenuList);
        }
        return rows;
    }

    @Override
    public List<Tenant> selectDepByUserId(Long userId) {
        return tenantMapper.selectDepByUserId(userId);
    }

    @Override
    public boolean checkPopulation(String tenantId) {
        Tenant department = tenantMapper.selectDepartmentByDepId(tenantId);
        int userNum = iBizTenantUserService.countUserNumByDepId(tenantId);
        if (department.getMaxPopulation() != -1 && department.getMaxPopulation() <= userNum) {
            return true;
        }
        return false;
    }

    @Override
    public int updateTenant(Tenant tenant) {
        return tenantMapper.updateDepartment(tenant);
    }

    @Override
    public void checkHouseNum(String tenantId) {
        Tenant tenant = tenantMapper.selectDepartmentByDepId(tenantId);
        if (tenant.getMaxHouse() != -1) {
            //校验房屋数量
            int houseNum = houseService.countHouseNumByTenantId(tenant.getTenantId());
            if (tenant.getMaxHouse() < houseNum) {
                throw new ServiceException("房屋最大数量小于当前机构房屋数量");
            }
        }
    }

    /**
     * 校验数据
     * @param tenant
     */
    public void checkDepartment(Tenant tenant){
        // if (tenant.getTypeList() == null || tenant.getTypeList().length == 0) {
        //     throw new ServiceException("机构类型为空");
        // }
        if (TenantConstants.DEP_PARENT_STATE_YES.equals(tenant.getDepParentState()) &&
                (tenant.getParentIdList() == null || tenant.getParentIdList().length == 0)) {
            throw new ServiceException("上级机构为空");
        }
        int result = tenantMapper.countDepByName(tenant.getTenantName(), tenant.getTenantId());
        if (result > 0) {
            throw new ServiceException("该机构名称已经存在");
        }
    }
}
